﻿using LdtJudge.DataEngine.Common;
using LdtJudge.DataEngine.Common.XmlUtility;
using LdtJudge.DataEngine.DataBaseStores;
using LdtJudge.DataEngine.Model.XMLConfigModel.CauseExtractModel;
using LdtJudge.DataEngine.Model.XMLConfigModel.DataStores;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;

namespace LdtDataEngin.ModuleDetail.AnalysisModule.CaseCauseFill
{
    /// <summary>
    /// 案由填充
    /// </summary>
    public class CaseCauseFillAssemble
    {
        /// <summary>
        /// 上下文
        /// </summary>
        public DataContext _dataContext;

        /// <summary>
        /// 模块名称
        /// </summary>
        public string _moudleName;

        /// <summary>
        /// 案由填充
        /// </summary>
        /// <param name="dataContext">上下文</param>
        /// <param name="moudleName">模块名称</param>
        public CaseCauseFillAssemble(DataContext dataContext,string moudleName)
        {
            _dataContext = dataContext;
            _moudleName = moudleName;
        }

        /// <summary>
        /// 案由数据填充
        /// </summary>
        public void CauseDataFill()
        {
            XmlUtilCommon xmlUtilCommon = new XmlUtilCommon() { dataContext = _dataContext };
            var configModel = _dataContext.DataLayerSys.GetConfigModel(_moudleName);
            CauseFillModel causeFill = null;
            //案由要素填充配置
            if(configModel.ConfigDetail != null && configModel.ConfigDetail.Exists(a => a.Code == "causefill"))
            {
                _dataContext.InteractiveShow.LogShow($"执行模块编号:{"causefill"} 执行code:{configModel.ConfigDetail.FirstOrDefault(a => a.Code == "causefill").ExecuteCode} 文件路径:{configModel.ConfigDetail.FirstOrDefault(a => a.Code == "causefill").FilePath}", LogMessageType.Info);
                var causeFillConfig = configModel.ConfigDetail.FirstOrDefault(x => x.Code == "causefill");
                if(!string.IsNullOrWhiteSpace(causeFillConfig.ConfigContent))
                    causeFill = XmlUtility.DeserializeToObject<CauseFillModel>(causeFillConfig.ConfigContent);
            }
            if (causeFill!= null)
            {
                //案件类型
                var causeCaseType = causeFill.CaseTypes.FirstOrDefault(x => x.Code.ToLower() == _dataContext.DataLayerAns.CaseType);
                if (causeCaseType != null && causeCaseType.Mergelement != null)
                {
                    //合并后要素路径
                    var mergPath = causeCaseType.Mergelement.Path;
                    if (!string.IsNullOrWhiteSpace(mergPath))
                    {
                        if (_dataContext.DataLayerAns.ElementAnalsisDataModelResults != null)
                        {
                            var adfds = JsonConvert.SerializeObject(_dataContext.DataLayerAns.AnalysisResultsDataModel.dataModelList);
                            foreach (var causeDicItem in _dataContext.DataLayerAns.ElementAnalsisDataModelResults)
                            {
                                string causeId = causeDicItem.Key;
                                List<DataModel> causeDatas = null;
                                List<DataModel> causeList = null;
                                if (causeDicItem.Value != null && causeDicItem.Value.Any())
                                {
                                    var causeNodeId = Snowflake.Instance().GetId().ToString();
                                    causeDatas = causeDicItem.Value.Select(x => x.Clone()).ToList();
                                    causeList = causeDicItem.Value.Select(x => x.Clone()).ToList();
                                    List<string> deleteIds = causeDatas.Select(x => x.ID).ToList();
                                    //事实要素节点添加要素类型属性
                                    foreach (var factItem in causeDatas.Where(x => x.ParentId == causeId))
                                    {
                                        if (factItem.XmlPath.EndsWith("事实要素") && !factItem.AttributesList.Any(x => x.Name == "要素类型"))
                                        {
                                            AttributeInfo attributeTmp = new AttributeInfo();
                                            attributeTmp.Name = "要素类型";
                                            attributeTmp.sourceList = new List<Source>();
                                            Source attrSource = new Source();
                                            attrSource.IsCheck = "1";
                                            attrSource.SourceCode = _dataContext.DataLayerAns.SourceCode;
                                            attrSource.SaveValue = "4";
                                            attributeTmp.sourceList.Add(attrSource);
                                            factItem.AttributesList.Add(attributeTmp);

                                            DataModel dataModel = causeList.FirstOrDefault(a => a.ID == factItem.ID);
                                            dataModel.AttributesList.Add(attributeTmp);
                                        }
                                    }
                                    xmlUtilCommon.DataModelIDByResets(causeDatas, causeId, causeNodeId);
                                    string path = mergPath.Replace("{causecode}", causeId);
                                    xmlUtilCommon.CaseNodeUpdate(_dataContext.DataLayerAns.AnalysisResultsDataModel.dataModelList, path);
                                    string causeParentId = XmlUtility.ConditionFirstOrDefaultDataModel(_dataContext.DataLayerAns.AnalysisResultsDataModel.dataModelList, "", path)?.ID;
                                    causeDatas.FirstOrDefault(x => x.ID == causeId).ParentId = causeParentId;
                                    causeDatas.FirstOrDefault(x => x.ID == causeId).ID = causeNodeId;
                                    _dataContext.DataLayerAns.AnalysisResultsDataModel.dataModelList.AddRange(causeDatas);
                                    XmlDocument xmlDocument= xmlUtilCommon.DataModelByXml(causeDatas, causeParentId);
                                    if (_dataContext.DataLayerOpt.MergeElementXml==null)
                                    {
                                        _dataContext.DataLayerOpt.MergeElementXml = new Dictionary<string, XmlDocument>();
                                        _dataContext.DataLayerOpt.MergeElementDataList = new Dictionary<string, List<DataModel>>();

                                    }
                                    if (_dataContext.DataLayerOpt.MergeElementXml.ContainsKey(causeId))
                                    {
                                        _dataContext.DataLayerOpt.MergeElementXml[causeId] = xmlDocument;
                                        _dataContext.DataLayerOpt.MergeElementDataList[causeId] = causeList;
                                    }
                                    else
                                    {
                                        _dataContext.DataLayerOpt.MergeElementXml.Add(causeId,xmlDocument);
                                        _dataContext.DataLayerOpt.MergeElementDataList.Add(causeId, causeList);
                                    }
                                    if (deleteIds!=null && deleteIds.Any())
                                        _dataContext.DataLayerAns.AnalysisResultsDataModel.dataModelList.RemoveAll(x => deleteIds.Contains(x.ID));
                                }
                            }
                        }
                    }
                }
            }

            if (_dataContext.DataLayerAns.AnalysisResultsDataModel.dataModelList != null)
                _dataContext.DataLayerAns.AnalysisResultsXml = XmlUtility.DataModelByXml(_dataContext.DataLayerAns.AnalysisResultsDataModel.dataModelList);
        }
    }
}
